// src/api/services/authService.ts
import { apiClient } from '../config'
import type {
  AccountLoginParams,
  AccountLoginResponse,
  EmailCodeParams,
  EmailCodeResponse,
  EmailLoginParams,
  EmailLoginResponse,
  UserInfo,
} from '../../types/Login'

/**
 * 发送邮箱验证码 - GET 请求
 * @param params 邮箱参数
 * @returns 发送验证码响应
 */
export const sendEmailCode = async (params: EmailCodeParams): Promise<EmailCodeResponse> => {
  return await apiClient.get('/Login/EmailCode', { params })
}

/**
 * 邮箱验证码登录 - GET 请求
 * @param params 邮箱登录参数
 * @returns 登录响应
 */
export const emailLogin = async (params: EmailLoginParams): Promise<EmailLoginResponse> => {
  return await apiClient.get('/Login/EmailLogin', { params })
}

/**
 * 账号密码登录 - 根据你的实际接口调整
 * @param params 登录参数
 * @returns 登录响应
 */
export const accountLogin = async (params: AccountLoginParams): Promise<AccountLoginResponse> => {
  return await apiClient.get('/Login/AccountLogin', { params })
}

/**
 * 退出登录
 * @returns 退出登录响应
 */
export const logout = async (): Promise<void> => {
  // 根据你的实际接口调整
  await apiClient.post('/Login/Logout')
  // 清除本地存储的token和用户信息
  clearUserInfo()
}

/**
 * 刷新token
 * @returns 新的token
 */
export const refreshToken = async (): Promise<{ token: string }> => {
  return await apiClient.post('/auth/refresh')
}

// 保存 token
export const saveToken = (token: string): void => {
  localStorage.setItem('token', token)
}

// 保存用户信息
export const saveUserInfo = (userInfo: UserInfo): void => {
  localStorage.setItem('userInfo', JSON.stringify(userInfo))
}

// 获取用户信息
export const getUserInfo = (): UserInfo | null => {
  const userInfoStr = localStorage.getItem('userInfo')
  return userInfoStr ? JSON.parse(userInfoStr) : null
}

// 清除用户信息
export const clearUserInfo = (): void => {
  localStorage.removeItem('userInfo')
  localStorage.removeItem('token')
}

export default {
  accountLogin,
  sendEmailCode,
  emailLogin,
  logout,
  refreshToken,
  saveToken,
}
